package com.mmall.common;

import com.mmall.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * http 前后监听工具
 * Created by pc on 2019/3/23.
 */
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter{
    private static final String START_TIME = "requestStartTime";

    /**
     * 请求前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String url = request.getRequestURL().toString();
           Map paramterMap = request.getParameterMap();
           log.info("request start url:{},param:{}",url, JsonMapper.obj2String(paramterMap));
           request.setAttribute(START_TIME,System.currentTimeMillis());
        return true;
    }

    /**
     * 只在正常完成下响应
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       /* String url = request.getRequestURL().toString();
        Map paramterMap = request.getParameterMap();
        log.info("request finish url:{},param:{}",url, JsonMapper.obj2String(paramterMap));*/
    }

    /**
     * 请求完成后 在任何情况下都会响应的 包括发生异常
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURL().toString();
        Map paramterMap = request.getParameterMap();
        long endTime = (Long) request.getAttribute(START_TIME);
        long finishedTime = System.currentTimeMillis() - endTime;
        log.info("finishedTime:{} ",finishedTime/1000+"秒");
        log.info("request Exception finish url:{},param:{}",url, JsonMapper.obj2String(paramterMap));
    }
}
